package com.ray.kmm.android

import android.app.Activity
import android.app.AlertDialog
import android.content.Context
import android.content.DialogInterface
import android.content.Intent
import android.graphics.Bitmap
import android.net.Uri
import android.os.Bundle
import android.text.InputType
import android.util.Log
import android.view.ViewGroup
import android.webkit.JavascriptInterface
import android.widget.EditText
import androidx.activity.ComponentActivity
import com.ray.kmm.android.utils.WebViewJavaScriptFunction
import com.tencent.smtt.export.external.interfaces.GeolocationPermissionsCallback
import com.tencent.smtt.export.external.interfaces.JsPromptResult
import com.tencent.smtt.export.external.interfaces.JsResult
import com.tencent.smtt.export.external.interfaces.WebResourceRequest
import com.tencent.smtt.export.external.interfaces.WebResourceResponse
import com.tencent.smtt.sdk.ValueCallback
import com.tencent.smtt.sdk.WebChromeClient
import com.tencent.smtt.sdk.WebSettings
import com.tencent.smtt.sdk.WebView
import com.tencent.smtt.sdk.WebViewClient
import java.io.File
import java.io.FileInputStream
import java.io.InputStream

/**
 * description ：X5浏览器
 * @author : ray
 * @date : 2023/8/31
 */
class X5WebViewActivity : ComponentActivity() {
    protected var mWebView: WebView? = null
    private val DISABLE_ALPHA = 120
    private val ENABLE_ALPHA = 255
    private val FILE_CHOOSER_REQUEST = 100
    private val mHomeUrl = "https://wwww.baidu.com"
    protected val TAG = "X5WebViewActivity"

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_webview)
        initView()
    }

    fun initView() {
        val context: Context = this
        mWebView = WebView(context)
        val mContainer = findViewById<ViewGroup>(R.id.webViewContainer)
        mContainer.addView(mWebView)

        val webSetting: WebSettings = mWebView!!.settings
        webSetting.setJavaScriptEnabled(true)
        webSetting.setAllowFileAccess(true)
        webSetting.setSupportZoom(true)
        webSetting.setDatabaseEnabled(true)
        webSetting.setAllowFileAccess(true)
        webSetting.setDomStorageEnabled(true)

        initWebViewClient()
        initWebChromeClient()
        initJavaScriptInterface()

        mWebView!!.loadUrl(mHomeUrl)
    }

    private fun initWebViewClient() {
        mWebView!!.setWebViewClient(object : WebViewClient() {
            override fun shouldOverrideUrlLoading(view: WebView, url: String): Boolean {
                // 返回true代表在当前webview中打开，返回false表示打开浏览器
                view.loadUrl(url)
                // 4.0 之后必须添加该设置
                // 只能加载 http:// 和 https:// 页面 , 不能加载其它协议链接
                if (url.startsWith("http://") || url.startsWith("https://")) {
                    view.loadUrl(url)
                    return true
                } else {
                    if (url.startsWith("weixin://") ||
                        url.startsWith("alipays://") ||
                        url.startsWith("tel://") ||
                        url.startsWith("baiduboxapp://") ) {
                        val intent = Intent(Intent.ACTION_VIEW, Uri.parse(url))
                        startActivity(intent)
                        return true
                    }
                }
                return super.shouldOverrideUrlLoading(view, url);
            }
            /**
             * 具体接口使用细节请参考文档：
             * https://x5.tencent.com/docs/webview.html
             * 或 Android WebKit 官方：
             * https://developer.android.com/reference/android/webkit/WebChromeClient
             */
            override
            fun onPageStarted(view: WebView, url: String, favicon: Bitmap?) {
                Log.i(TAG, "onPageStarted, view:$view, url:$url")
            }

            override
            fun onPageFinished(view: WebView, url: String) {
                Log.i(TAG, "onPageFinished, view:$view, url:$url")
            }

            override
            fun onReceivedError(
                webView: WebView?,
                errorCode: Int,
                description: String,
                failingUrl: String
            ) {
                Log.e(
                    TAG, "onReceivedError: " + errorCode
                            + ", description: " + description
                            + ", url: " + failingUrl
                )
            }

            override
            fun shouldInterceptRequest(
                webView: WebView?,
                webResourceRequest: WebResourceRequest
            ): WebResourceResponse? {
                return if (webResourceRequest.getUrl().toString().contains("debugdebug")) {
                    var `in`: InputStream? = null
                    Log.i("AterDebug", "shouldInterceptRequest")
                    try {
                        `in` = FileInputStream(File("/sdcard/1.png"))
                    } catch (e: Exception) {
                    }
                    WebResourceResponse("image/*", "utf-8", `in`)
                } else {
                    super.shouldInterceptRequest(webView, webResourceRequest)
                }
            }
        })
    }

    private fun initWebChromeClient() {
        val context: Context = this
        val activity: Activity = this
        mWebView!!.setWebChromeClient(object : WebChromeClient() {
            /**
             * 具体接口使用细节请参考文档：
             * https://x5.tencent.com/docs/webview.html
             * 或 Android WebKit 官方：
             * https://developer.android.com/reference/android/webkit/WebChromeClient
             */
            override
            fun onProgressChanged(view: WebView, newProgress: Int) {
                Log.i(TAG, "onProgressChanged, newProgress:$newProgress, view:$view")
            }

            override
            fun onJsAlert(
                webView: WebView?,
                url: String?,
                message: String?,
                result: JsResult
            ): Boolean {
                AlertDialog.Builder(context).setTitle("JS弹窗Override")
                    .setMessage(message)
                    .setPositiveButton(
                        "OK"
                    ) { dialogInterface: DialogInterface?, i: Int -> result.confirm() }
                    .setCancelable(false)
                    .show()
                return true
            }

            override
            fun onJsConfirm(
                webView: WebView?,
                url: String?,
                message: String?,
                result: JsResult
            ): Boolean {
                AlertDialog.Builder(context).setTitle("JS弹窗Override")
                    .setMessage(message)
                    .setPositiveButton(
                        "OK"
                    ) { dialogInterface: DialogInterface?, i: Int -> result.confirm() }
                    .setNegativeButton(
                        "Cancel"
                    ) { dialogInterface: DialogInterface?, i: Int -> result.cancel() }
                    .setCancelable(false)
                    .show()
                return true
            }

            override
            fun onJsBeforeUnload(
                webView: WebView?,
                url: String?,
                message: String?,
                result: JsResult
            ): Boolean {
                AlertDialog.Builder(context).setTitle("页面即将跳转")
                    .setMessage(message)
                    .setPositiveButton(
                        "OK"
                    ) { dialogInterface: DialogInterface?, i: Int -> result.confirm() }
                    .setNegativeButton(
                        "Cancel"
                    ) { dialogInterface: DialogInterface?, i: Int -> result.cancel() }
                    .setCancelable(false)
                    .show()
                return true
            }

            override
            fun onJsPrompt(
                webView: WebView?,
                url: String?,
                message: String?,
                defaultValue: String?,
                result: JsPromptResult
            ): Boolean {
                val input = EditText(context)
                input.inputType =
                    InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_VARIATION_PASSWORD
                AlertDialog.Builder(context).setTitle("JS弹窗Override")
                    .setMessage(message)
                    .setView(input)
                    .setPositiveButton(
                        "OK"
                    ) { dialogInterface: DialogInterface?, i: Int ->
                        result.confirm(
                            input.text.toString()
                        )
                    }
                    .setCancelable(false)
                    .show()
                return true
            }

            /**
             * Return value usage see FILE_CHOOSE_REQUEST in
             * [BaseWebViewActivity.onActivityResult]
             */
            override
            fun onShowFileChooser(
                webView: WebView?,
                filePathCallback: ValueCallback<Array<Uri?>?>,
                fileChooserParams: WebChromeClient.FileChooserParams
            ): Boolean {
                Log.i(TAG, "openFileChooser: " + fileChooserParams.getMode())
                return true
            }

            override
            fun onGeolocationPermissionsShowPrompt(
                origin: String,
                geolocationPermissionsCallback: GeolocationPermissionsCallback
            ) {
//                if (verifyLocationPermissions(activity)) {
//                    geolocationPermissionsCallback.invoke(origin, true, false)
//                } else {
//                    locationPermissionUrl = origin
//                    mGeolocationCallback = geolocationPermissionsCallback
//                }
            }
        })
    }

    private fun initJavaScriptInterface() {
//        val context: Activity = this
//        mWebView!!.addJavascriptInterface(object : WebViewJavaScriptFunction() {
//            fun onJsFunctionCalled(tag: String?) {}
//
//            @JavascriptInterface
//            fun openQRCodeScan() {
////                IntentIntegrator(context).initiateScan()
//            }
//
//            @JavascriptInterface
//            fun openDebugX5() {
//                mWebView!!.loadUrl("http://debugx5.qq.com")
//            }
//
//            @JavascriptInterface
//            fun openWebkit() {
////                startActivity(Intent(context, SystemWebViewActivity::class.java))
//            }
//        }, "Android")
    }

    override fun onDestroy() {
        if (mWebView != null) {
            mWebView!!.destroy()
        }
        super.onDestroy()
    }
}
